package office;

import com.spire.pdf.FileFormat;
import com.spire.pdf.PdfDocument;
import com.spire.pdf.PdfPageBase;
import com.spire.xls.ExcelVersion;
import com.spire.xls.Workbook;
import com.spire.xls.Worksheet;
import org.junit.jupiter.api.Test;

import java.io.FileWriter;
import java.io.IOException;

public class T1 {
    public static String file = "F:/移通/大四上/刘津宇(2022-2023-1)课表.pdf";
    public static String excel = "PDFToXLS.xlsx";
    @Test
    public void t0() {
        PdfDocument pdf = new PdfDocument();

        //加载PDF文档
        pdf.loadFromFile("F:/移通/大四上/刘津宇(2022-2023-2)课表.pdf");

        //保存为Excel
        pdf.saveToFile(excel, FileFormat.XLSX);
    }

    @Test
    public void t2() {

        //创建PdfDocument实例
        PdfDocument doc = new PdfDocument();
        //加载PDF文件
        doc.loadFromFile("F:/移通/大四上/刘津宇(2022-2023-1)课表.pdf");

        //创建StringBuilder实例
        StringBuilder sb = new StringBuilder();

        PdfPageBase page;
        //遍历PDF页面，获取每个页面的文本并添加到StringBuilder对象
        for (int i = 0; i < doc.getPages().getCount(); i++) {
            page = doc.getPages().get(i);
            sb.append(page.extractText(true));
        }
        FileWriter writer;
        try {
            //将StringBuilder对象中的文本写入到文本文件
            writer = new FileWriter("ExtractText.txt");
            writer.write(sb.toString());
            writer.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }

        doc.close();
    }

    @Test
    public void t3() {
        //加载测试文档
        Workbook wb = new Workbook();
        wb.loadFromFile(excel);

        //获取第一个工作表
        Worksheet sheet = wb.getWorksheets().get(0);

        //遍历所有行
        for (int i = sheet.getLastRow(); i >= 1; i--) {
            //判断行是否空白
            if (sheet.getRows()[i - 1].isBlank()) {
                //删除指定行
                sheet.deleteRow(i);
            }
        }

        //遍历所有列
        for (int j = sheet.getLastColumn(); j >= 1; j--) {
            //判断列是否空白
            if (sheet.getColumns()[j - 1].isBlank()) {
                //删除指定列
                sheet.deleteColumn(j);
            }
        }

        //保存文档
        wb.saveToFile(excel, ExcelVersion.Version2016);
    }

}
